package com.nuatar.meibi;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.nuatar.meibi.pubvar.Configer;
import com.nuatar.meibi.pubvar.LAdapter;
import com.nuatar.meibi.pubvar.LAdapter.ViewBinder;
import com.nuatar.meibi.pubvar.MyImageButton;
import com.nuatar.meibi.pubvar.MyPagerAdapter;
import com.nuatar.meibi.pubvar.NetBus;
import com.nuatar.meibi.pubvar.PhoneMaster;
import com.nuatar.meibi.pubvar.PostMan;
import com.nuatar.meibi.pubvar.SqlBus;
import com.nuatar.meibi.pubvar.UpdateListener;
import com.nuatar.meibi.pubvar.WallPaper;
import com.tencent.exmobwin.MobWINManager;
import com.tencent.exmobwin.Type;
import com.tencent.updatesdk.UpdateSDK;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends FatherActivity {
	LAdapter newad, hotad, hisad;
	MeiBi mb;
	private MyPagerAdapter mpg;
	private ViewPager mPager;
	private String imei;
	private int colnum;
	static MyHandler myHandler;
	static Handler tHandler;
	String ScreenInfo;
	private TextView t1, t2, t3;
	private int currIndex = 0;
	GridView gvhis, gvnew, gvhot;
	private List<View> listViews;
	

	class MyHandler extends Handler {
		public MyHandler() {
		}

		//
		@Override
		public void handleMessage(Message msg) {
			SharedPreferences pre = PreferenceManager
					.getDefaultSharedPreferences(getApplicationContext());
			int coins=pre.getInt("MyCoins", 0);
			TextView CoinText=(TextView) findViewById(R.id.CoinText);
			CoinText.setText("积分: "+coins);
			if (msg.what == 1) {
				newad.notifyDataSetChanged();
			} else if (msg.what == 2) {
				hotad.notifyDataSetChanged();
			}
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		TelephonyManager telephonyManager = (TelephonyManager) this
				.getSystemService(Context.TELEPHONY_SERVICE);
		imei = PhoneMaster.getMD5Str(telephonyManager.getDeviceId());
		
		String aa = "/data/data/com.nuatar.meibi/databases/mydata.db";
		File f = new File(aa);
		if (null == f || !f.exists()) {
			MT mt = new MT();
			new Thread(mt).start();
			
		}
		CrashHandler crashHandler = CrashHandler.getInstance();
		crashHandler.init(this);
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		colnum = dm.widthPixels / Configer.ImageWidth;
		ScreenInfo = "density:" + dm.density + "Screen" + dm.widthPixels + "-"
				+ dm.heightPixels;
		MobWINManager.init(this, Type.MOBWIN_BANNER);

		setContentView(R.layout.activity_main);
		listViews = new ArrayList<View>();
		gvhis = new GridView(this);
		gvnew = new GridView(this);
		gvhot = new GridView(this);
		myHandler = new MyHandler();
		mb = (MeiBi) this.getApplication();
		mb.context = this.getApplicationContext();
		SqlBus sb = new SqlBus(this.getApplicationContext());
		sb.InnitDatabase();
		OnItemClickListener ocl = new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Item点击处理
				SharedPreferences pre = PreferenceManager
						.getDefaultSharedPreferences(getApplicationContext());
				int coins=pre.getInt("MyCoins", 0);
				SharedPreferences.Editor edt = pre.edit();
				SqlBus sb = new SqlBus(getApplicationContext());
				WallPaper wps = sb.getWallPaper(((MyImageButton)view).mwp.id);
				if(wps==null){
					if(coins>0){
						coins--;
						Toast.makeText(getApplicationContext(), "消费一个积分，当前剩余积分："+coins, Toast.LENGTH_LONG).show();
						edt.putInt("MyCoins", coins);
						edt.commit();
						Intent intent = new Intent();
						intent.setClass(MainActivity.this, ImagePool.class);
						mb.CurrentPaper = ((MyImageButton) view).mwp;
						mb.Curr = 0;
						startActivity(intent);
					}else{
							new AlertDialog.Builder(MainActivity.this)
							.setTitle("积分不足")
							.setMessage("是否推荐好友来赚取积分？")
							.setIcon(R.drawable.ic_launcher)
							.setPositiveButton("确定", new DialogInterface.OnClickListener() {
							@Override
							public
							void onClick(DialogInterface dialog, int whichButton) {
							setResult(RESULT_OK);
							Intent intent = new Intent();
							intent.setClass(MainActivity.this, ShareActivity.class);
							startActivity(intent);
							}
							})
							.setNegativeButton("取消", new DialogInterface.OnClickListener() {
							@Override
							public
							void onClick(DialogInterface dialog, int whichButton) {
								
							}
							})
							.show();	
					}
				}else{
					Intent intent = new Intent();
					intent.setClass(MainActivity.this, ImagePool.class);
					mb.CurrentPaper = ((MyImageButton) view).mwp;
					mb.Curr = 0;
					startActivity(intent);
				}
				
				
			}
		};
		ViewBinder vb = new ViewBinder() {
			@Override
			public View getView(int position, Context ctx, Object data) {
				MyImageButton mib = new MyImageButton(ctx, (WallPaper) data);
				GridView.LayoutParams param = new GridView.LayoutParams(
						LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
				mib.setLayoutParams(param);
				 mib.setPadding(0, 0, 0, 0);
				return mib;

			}

			@Override
			public View update(View v, int position, Object data) {
				// TODO 自动生成的方法存根
				((MyImageButton) v).UpdateImage();
				return v;
			}
		};

		tHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				Bundle b = msg.getData();
				String result = b.getString("test");
				TextView ivs = (TextView) findViewById(R.id.ImageTittle);
				ivs.setText(result);
			}
		};
		newad = new LAdapter(mb.context, null, vb);
		hotad = new LAdapter(mb.context, null, vb);

		gvnew.setNumColumns(colnum);
		gvnew.setPadding(5, 0, 0, 0);
		gvnew.setAdapter(newad);
		gvnew.setSelector(new ColorDrawable(Color.TRANSPARENT));
		gvnew.setGravity(Gravity.CENTER);
		gvnew.setVerticalSpacing(5);
		gvnew.setHorizontalSpacing(5);
		gvhot.setNumColumns(colnum);
		gvhot.setAdapter(hotad);
		gvhot.setGravity(Gravity.CENTER);
		gvhot.setPadding(5, 0, 0, 0);
		gvhot.setVerticalSpacing(0);
		gvhot.setSelector(new ColorDrawable(Color.TRANSPARENT));
		gvhot.setVerticalSpacing(5);
		gvhot.setHorizontalSpacing(5);
		mb.hislist = new ArrayList<WallPaper>();
		listViews.add(gvnew);
		listViews.add(gvhot);
		sb.innitLocals(mb);
		if (null != mb.hislist && 0 < mb.hislist.size()) {
			hisad = new LAdapter(mb.context, mb.hislist, vb);
			gvhis.setNumColumns(colnum);
			gvhis.setGravity(Gravity.CENTER);
			gvhis.setAdapter(hisad);
			gvhis.setPadding(5, 0, 0, 0);
			gvhis.setVerticalSpacing(5);
			gvhis.setHorizontalSpacing(5);
			gvhis.setSelector(new ColorDrawable(Color.TRANSPARENT));
			listViews.add(gvhis);
		} else {
			LayoutInflater inflater = LayoutInflater.from(mb.context);
			View gvhis = inflater.inflate(R.layout.history_none, null);
			listViews.add(gvhis);
		}
		gvnew.setOnItemClickListener(ocl);
		gvhot.setOnItemClickListener(ocl);
		gvhis.setOnItemClickListener(ocl);
		newThread ns = new newThread(1);
		new Thread(ns).start();
		Button SugBtn = (Button) findViewById(R.id.ReplyBtn);
		SugBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent.setClass(MainActivity.this, SugActivity.class);
				startActivity(intent);
			}
		});
		InitTextView();
		setTextWhite(0);
		InitViewPager();
		SharedPreferences pre = PreferenceManager
				.getDefaultSharedPreferences(this.getApplicationContext());
		String Keys = "MeikUseTime";
		String AutoKey = "AutoUpdate";
		String UpdateKey = "UpdateQue";
		String upQue = pre.getString(UpdateKey, "NO");
		String datestr=pre.getString(Keys, "20130101000000");
		int coins=pre.getInt("MyCoins", 0);
		SharedPreferences.Editor edt = pre.edit();
		if (upQue.equals("NO")) {
			edt.putBoolean(AutoKey, true);
			edt.putString(UpdateKey, "15");
			AlertDialog.Builder Alb=new AlertDialog.Builder(this);
			Alb.setTitle("强力提示！");
			Alb.setMessage("在设置中开启强图模式，返回主界面后刷新可以观看更多强图哦！！\n第一次加载会比较缓慢，请耐心等待");
			Alb.create().show();
		}
		Date tm = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		try {//获取存储的时间戳信息
			Date th=sdf.parse(datestr);
			if(!PhoneMaster.DateCmp(tm, th)){
				coins+=5;
			Toast.makeText(getApplicationContext(), "每日赠送5个积分", Toast.LENGTH_LONG).show();
			}
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		TextView CoinText=(TextView) findViewById(R.id.CoinText);
		CoinText.setText("积分: "+coins);
		String time = sdf.format(tm);
		edt.putInt("MyCoins", coins);
		edt.putString(Keys, time);
		edt.commit();
		final UpdateListener updateListener = new UpdateListener(this);
		UpdateSDK.checkUpdate(getApplicationContext(), updateListener);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub

		String title = (String) item.getTitle();
		if (title == this.getResources().getText(R.string.exit)) {

			System.exit(0);

		} else if (title == this.getResources().getText(R.string.Settings)) {
			Intent intent = new Intent();
			intent.setClass(MainActivity.this, SettingsActivity.class);
			startActivity(intent);
		} else if (title == this.getResources().getText(R.string.CleanLocals)) {
			String savePath = Environment.getExternalStorageDirectory()
					.getPath() + Configer.DirHead;
			deleteAllFile(savePath);
			SqlBus sb = new SqlBus(this.getApplicationContext());
			sb.clearFeedTable("WallPaper");
			Toast.makeText(this.getApplicationContext(), "清理成功！重启应用生效",
					Toast.LENGTH_LONG).show();

		} else if (title == this.getResources().getText(R.string.ReFresh)) {
			newad.Clear();
			hotad.Clear();
			newThread ns = new newThread(200);
			new Thread(ns).start();
		}else if (title == this.getResources().getText(R.string.MsgCenter)) {
			Intent intent = new Intent();
			intent.setClass(MainActivity.this, MessageCenter.class);
			startActivity(intent);
		}else if (title == this.getResources().getText(R.string.singleInfo)) {
			Toast.makeText(getApplicationContext(), "功能正在建设中，稍后版本推出", Toast.LENGTH_LONG).show();
		}
		return true;
	}

	@Override
	protected void onStart() {
		super.onStart();
		mGaTracker.sendView(this.toString());
	}

	@Override
	protected void onResume() {
		super.onResume();

	}

	@Override
	protected void onDestroy() {
		MobWINManager.destroy();
		super.onDestroy();
	}

	class newThread implements Runnable {
		private long time;
		ProgressDialog pdialog=ProgressDialog.show(MainActivity.this, null, "加载中，请稍后……");
		public newThread(long times) {
			time = times;
		}

		@Override
		public void run() {
			// TODO 自动生成的方法存根
			
			try {
				Thread.sleep(time);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			List<WallPaper> nb; 
			List<WallPaper> hb ;
			SharedPreferences pre = PreferenceManager
					.getDefaultSharedPreferences(getApplicationContext());
			boolean IsVIP=pre.getBoolean("IsVIP", false);
			if(!IsVIP){
				nb=NetBus.getNew();
				hb=NetBus.getHots();
			}else{
				nb=NetBus.getNewVIP();
				hb=NetBus.getHotsVIP();
			}
			newad.mlist = new ArrayList<WallPaper>();
			MainActivity.myHandler.sendEmptyMessage(1);
			for (int i = 0; i < nb.size(); i++) {
				WallPaper wp = nb.get(i);
				if (NetBus.downloadDesFile(wp.id, null)) {
					wp = PhoneMaster.setWallPaperImagePairs(wp);
					newad.mlist.add(wp);
					MainActivity.myHandler.sendEmptyMessage(1);
				}
			}
			hotad.mlist = new ArrayList<WallPaper>();
			MainActivity.myHandler.sendEmptyMessage(2);
			for (int i = 0; i < hb.size(); i++) {
				WallPaper wp = hb.get(i);
				if (NetBus.downloadDesFile(wp.id, null)) {
					wp = PhoneMaster.setWallPaperImagePairs(wp);
					hotad.mlist.add(wp);
					MainActivity.myHandler.sendEmptyMessage(2);
				}

			}
			pdialog.dismiss();
		}
	}

	class MT implements Runnable {

		@Override
		public void run() {
			String PhoneInfo = "Board:" + Build.BOARD + "-Brand:" + Build.BRAND
					+ "-Model:" + Build.MODEL + "-HardWare:" + Build.HARDWARE;
			Map<String, String> params = new HashMap<String, String>();
			params.put("info", "Device:" + imei + "PhoneInfo:" + PhoneInfo
					+ "ScreenInfo:" + ScreenInfo);
			String a = PostMan
					.submitPostData(params, "UTF-8", "action=SoftLog");
			Log.i("REGISTER", "Reg" + a);
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			new AlertDialog.Builder(MainActivity.this)
			.setTitle("退出提示")
			.setMessage("你要退了了么？")
			.setIcon(R.drawable.ic_launcher)
			.setPositiveButton("取消", new DialogInterface.OnClickListener() {
			@Override
			public
			void onClick(DialogInterface dialog, int whichButton) {
			
			}
			})
			.setNegativeButton("确定", new DialogInterface.OnClickListener() {
			@Override
			public
			void onClick(DialogInterface dialog, int whichButton) {
				setResult(RESULT_OK);
				System.exit(0);
			}
			})
			.show();
			System.exit(0);
			return false;
		}
		return false;
	}

	private void InitTextView() {
		t1 = (TextView) findViewById(R.id.newText);
		t2 = (TextView) findViewById(R.id.hotText);
		t3 = (TextView) findViewById(R.id.hisText);

		t1.setOnClickListener(new MyOnClickListener(0));
		t2.setOnClickListener(new MyOnClickListener(1));
		t3.setOnClickListener(new MyOnClickListener(2));
	}

	public void setTextWhite(int i) {
		currIndex = i;
		t1.setTextColor(Color.BLACK);
		t2.setTextColor(Color.BLACK);
		t3.setTextColor(Color.BLACK);
		switch (i) {
		case 0:
			t1.setTextColor(Color.WHITE);
			break;
		case 1:
			t2.setTextColor(Color.WHITE);
			break;
		case 2:
			t3.setTextColor(Color.WHITE);
			break;
		default:
			break;
		}
	}

	public class MyOnClickListener implements View.OnClickListener {
		private int index = 0;

		public MyOnClickListener(int i) {
			index = i;
		}

		@Override
		public void onClick(View v) {
			mPager.setCurrentItem(index);
			setTextWhite(index);
		}
	}

	private void InitViewPager() {
		mPager = (ViewPager) findViewById(R.id.Vpager);

		mpg = new MyPagerAdapter(listViews);
		mPager.setAdapter(mpg);
		mPager.setCurrentItem(0);

		mPager.setOnPageChangeListener(new MyOnPageChangeListener());
	}

	public class MyOnPageChangeListener implements OnPageChangeListener {

		@Override
		public void onPageSelected(int arg0) {
			currIndex = arg0;
			setTextWhite(currIndex);
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {

		}

		@Override
		public void onPageScrollStateChanged(int arg0) {

		}
	}

	public static boolean deleteAllFile(String folderFullPath) {
		boolean ret = false;
		try {
			File file = new File(folderFullPath);
			if (file.exists()) {
				if (file.isDirectory()) {
					File[] fileList = file.listFiles();
					for (int i = 0; i < fileList.length; i++) {
						String filePath = fileList[i].getPath();
						deleteAllFile(filePath);
					}
				}
				if (file.isFile()) {
					file.delete();
				}
			}
			ret = true;
		} catch (Exception e) {
			ret = false;
		}
		return ret;
	}

}
